package com.example.handler

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

/**
 一，handler原理
 1.Handler
 sendMessageAtTime():发送消息
 dispatchMessage(msg):分发消息 触发handleMessage对消息进行处理
 handleMessage():处理消息，重写的

 2.Message
 when:时间戳
 target:消息的接收者handler
 callback：使用post方式发送消息，本身是runnable对象

 3.MessageQueue
 enqueueMessage():将消息放到消息队列中

 4.Looper:
 loop():死循环不断从消息队列中取消息     msg.target.dispatchMessage(msg);

 */
class MainActivity : AppCompatActivity() {
    private lateinit var handler2:Handler

    private val handler:Handler = object :Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if(msg.what == 1){
                Toast.makeText(this@MainActivity,"子线程发送的消息 ${msg.obj}",Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        MyThread().start()



    }

   inner class MyThread:Thread(){

        override fun run() {
            super.run()


            val message = Message.obtain() //消息池，复用消息对象，最多50个
            val message2 = Message() //每次创建新的对象
            message.what = 1
            message.obj = "Hello"
            //111
            handler.sendMessageDelayed(message,5000)
            handler.post(object : Runnable {
                override fun run() {
                        Toast.makeText(this@MainActivity,"更新UI",Toast.LENGTH_SHORT).show()
                }
            })

            //子线程创建handler
            Looper.prepare()
            handler2 = Handler()
            Looper.loop()


        }
    }
}